use crate::role::{Role, dao::RoleDAO};
use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::Json,
};
use std::sync::Arc;
use sqlx::sqlite::SqlitePool;

// 数据库连接池类型
type Db = Arc<SqlitePool>;

// 获取所有角色
pub async fn list_roles(State(db): State<Db>) -> Result<Json<Vec<Role>>, (StatusCode, String)> {
    let role_dao = RoleDAO::new(db);
    match role_dao.list_roles().await {
        Ok(roles) => Ok(Json(roles)),
        Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
    }
}

// 创建新角色
pub async fn create_role(State(db): State<Db>, Json(role): Json<Role>) -> Result<Json<Role>, (StatusCode, String)> {
    let role_dao = RoleDAO::new(db);
    match role_dao.create_role(&role).await {
        Ok(id) => {
            let new_role = Role {
                id: Some(id),
                name: role.name,
                description: role.description,
            };
            Ok(Json(new_role))
        },
        Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
    }
}

// 根据ID获取角色
pub async fn get_role(State(db): State<Db>, Path(id): Path<i32>) -> Result<Json<Role>, (StatusCode, String)> {
    let role_dao = RoleDAO::new(db);
    match role_dao.get_role(id).await {
        Ok(Some(role)) => Ok(Json(role)),
        Ok(None) => Err((StatusCode::NOT_FOUND, "Role not found".to_string())),
        Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
    }
}

// 更新角色
pub async fn update_role(State(db): State<Db>, Path(id): Path<i32>, Json(role): Json<Role>) -> Result<Json<Role>, (StatusCode, String)> {
    let role_dao = RoleDAO::new(db);
    match role_dao.update_role(id, &role).await {
        Ok(true) => {
            let updated_role = Role {
                id: Some(id),
                name: role.name,
                description: role.description,
            };
            Ok(Json(updated_role))
        },
        Ok(false) => Err((StatusCode::NOT_FOUND, "Role not found".to_string())),
        Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
    }
}

// 删除角色
pub async fn delete_role(State(db): State<Db>, Path(id): Path<i32>) -> Result<StatusCode, (StatusCode, String)> {
    let role_dao = RoleDAO::new(db);
    match role_dao.delete_role(id).await {
        Ok(true) => Ok(StatusCode::NO_CONTENT),
        Ok(false) => Err((StatusCode::NOT_FOUND, "Role not found".to_string())),
        Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
    }
}